<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" v-hasPermi="['admin:goodsInfo:add']">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增商品
        </el-button>
      </el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="商品ID:">
        <el-input v-model="queryParams.goodsId" placeholder="请输入商品ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称:">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户ID:" v-hasPermi="['admin:goodsInfo:audit']">
        <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺ID:" v-hasPermi="['admin:goodsInfo:audit']">
        <el-input v-model="queryParams.shopId" placeholder="请输入店铺ID" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺名称:" v-hasPermi="['admin:goodsInfo:audit']">
        <el-input v-model="queryParams.shopName" placeholder="请输入店铺名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择商品分类" clearable size="small" style="width: 240px">
          <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
            :value="item.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable size="small" style="width: 240px">
          <el-option v-for="item in auditStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsStatus">
        <el-select v-model="queryParams.goodsStatus" placeholder="请选择商品状态" clearable size="small" style="width: 240px">
          <el-option v-for="item in goodsStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="商品信息" align="center" width="400px">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: left; align-items: center">
            <el-image :src="requestUrl + scope.row.mainImg" style="
                width: 140px;
                height: 100px;
                float: center;
                display: inline-block;
              " />
            <span style="
                width: 100%;
                text-align: left;
                box-sizing: border-box;
                padding-left: 5px;
              ">{{ scope.row.goodsName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="categoryName" />
      <el-table-column label="商品价格" align="center" prop="goodsPrice" />
      <el-table-column label="商品库存" align="center" prop="goodsStock" />
      <el-table-column label="销量" align="center" prop="saleCnt" />
      <el-table-column label="排序" align="center" prop="sortNum" />
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <span v-show="scope.row.auditStatus === -1">审核拒绝</span>
          <span v-show="scope.row.auditStatus === 0">待审核</span>
          <span v-show="scope.row.auditStatus === 1">审核通过</span>
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center" prop="goodsStatus">
        <template slot-scope="scope">
          <span v-show="scope.row.goodsStatus === 0">下架</span>
          <span v-show="scope.row.goodsStatus === 1">上架</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handlesort(scope.row)">排序
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-check" v-show="scope.row.auditStatus === 0"
            @click="audit(scope.row, 1)" v-hasPermi="['admin:goodsInfo:audit']">审核通过
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-close" v-show="scope.row.auditStatus === 0"
            @click="audit(scope.row, -1)" v-hasPermi="['admin:goodsInfo:audit']">审核拒绝
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-top"
            v-show="scope.row.auditStatus != 0 && scope.row.goodsStatus === 0" @click="putOnOrDown(scope.row, 1)"
            v-hasPermi="['admin:goodsInfo:putaway']">上架
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-bottom"
            v-show="scope.row.auditStatus != 0 && scope.row.goodsStatus === 1" @click="putOnOrDown(scope.row, 0)"
            v-hasPermi="['admin:goodsInfo:soldOut']">下架
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['admin:goodsInfo:query']">详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:goodsInfo:edit']">编辑
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-show="scope.row.goodsStatus === 0" v-hasPermi="['admin:goodsInfo:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 查看 -->
    <el-dialog title="详情图" :visible.sync="open1" width="800px" append-to-body @close="cancel">
      <el-form ref="detailForm" :model="detailForm" :inline="true" label-width="120px">
        <el-form-item label="商品ID:">
          <el-row style="width: 580px">
            <el-col :span="24">{{ detailForm.goodsId }}</el-col>
          </el-row>
        </el-form-item>
        <br />
        <el-form-item label="商品名称:">
          <el-row style="width: 580px">
            <el-col :span="24">{{ detailForm.goodsName }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品分类:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.categoryName }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="店铺ID:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.shopId }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="店铺名称:">
          <el-row style="width: 580px">
            <el-col :span="24">{{ detailForm.shopName }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品价格:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.goodsPrice }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品原价:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.originalPrice }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品成本价:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.costPrice }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品库存:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.goodsStock }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品销量:">
          <el-row>
            <el-col :span="24">{{ detailForm.saleCnt }}</el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="发货地:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.address }}</el-col>
          </el-row>
        </el-form-item>
        <!-- <el-form-item label="赠送绿色积分:">
          <el-row style="width: 250px">
            <el-col :span="24">{{ detailForm.lgwAmt }}</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="赠送消费券:">
          <el-row>
            <el-col :span="24">{{ detailForm.consumeAmt }}</el-col>
          </el-row>
        </el-form-item> -->
        <el-form-item label="审核状态:">
          <el-row style="width: 250px">
            <el-col :span="24">
              <span v-show="detailForm.auditStatus === -1">审核拒绝</span>
              <span v-show="detailForm.auditStatus === 0">待审核</span>
              <span v-show="detailForm.auditStatus === 1">审核通过</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="商品状态:">
          <el-row style="width: 250px">
            <el-col :span="24">
              <span v-show="detailForm.goodsStatus === 0">下架</span>
              <span v-show="detailForm.goodsStatus === 1">上架</span>
            </el-col>
          </el-row>
        </el-form-item>
        <br />
        <el-form-item label="主图: ">
          <el-image :src="requestUrl + detailForm.mainImg" style="width: 140px; height: 140px"
            :preview-src-list="previewMainImgList" />
        </el-form-item>
        <br />
        <el-form-item label="详情图: ">
          <el-row style="width: 580px">
            <el-col :span="24">
              <el-image :src="item" v-for="(item, key) in previewDetailImgList" :key="key"
                style="width: 140px; height: 140px" :preview-src-list="previewDetailImgList" />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel1">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加商品 -->
    <el-dialog :title="title" :visible.sync="open2" width="800px" append-to-body @close="cancel">
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品分类">
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品原价" prop="originalPrice">
          <el-input v-model="form.originalPrice" placeholder="请输入商品原价" />
        </el-form-item>
        <el-form-item label="商品成本价" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入商品成本价" />
        </el-form-item>
        <el-form-item label="商品库存" prop="goodsStock">
          <el-input v-model="form.goodsStock" placeholder="请输入商品库存" />
        </el-form-item>
        <el-form-item label="商品销量" prop="saleCnt">
          <el-input v-model="form.saleCnt" placeholder="请输入商品销量" />
        </el-form-item>
        <!-- <el-form-item label="赠送绿色积分" prop="lgwAmt">
          <el-input v-model="form.lgwAmt" placeholder="请输入赠送绿色积分" />
        </el-form-item>
        <el-form-item label="赠送消费券" prop="consumeAmt">
          <el-input v-model="form.consumeAmt" placeholder="请输入赠送消费券" />
        </el-form-item> -->
        <el-form-item label="发货地" prop="address">
          <el-input v-model="form.address" placeholder="请输入发货地" />
        </el-form-item>
        <el-form-item label="封面图">
          <imageUpload :limit="1" :file-size="3" v-model="form.mainImg" />
        </el-form-item>
        <el-form-item label="商品详情图">
          <el-upload :limit="9" :action="upload.url" :headers="upload.headers" :file-list="fileList"
            :on-remove="handleRemove" :on-success="handleSuccess" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel2">取消</el-button>
      </div>
    </el-dialog>

    <!-- 商品排序 -->
    <el-dialog :title="titlesort" :visible.sync="opensort" width="500px" append-to-body @close="cancelsort">
      <el-form ref="formsort" :rules="rulessort" :model="formsort" label-width="120px">
        <el-form-item label="排序列表" prop="sortNum">
          <el-input-number v-model="formsort.sortNum" controls-position="right" :min="0" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormsort">确定</el-button>
        <el-button @click="cancelsort">取消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listGoodsInfo,
  audit,
  saveOrUpdate,
  listGoodsCategory,
  putOnOrDown,
  goodsInfoControllersort,
} from "@/api/admin/goodsInfo";
import { getToken } from "@/utils/auth";

export default {
  name: "goodsInfo",
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视频管理表格数据
      goodsList: [],
      goodsDetailsImgList: [],
      imgList: [],
      //上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin/upload/uploadImg/3",
      },
      resource: "1",
      dialogImageUrl: "",
      // 弹出层标题
      title: "",
      titlesort: '',
      // 是否显示弹出层
      open1: false,
      open2: false,
      opensort: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      auditStatusOptions: [
        {
          value: "0",
          label: "待审核",
        },
        {
          value: "1",
          label: "审核通过",
        },
        {
          value: "-1",
          label: "审核拒绝",
        },
      ],
      goodsStatusOptions: [
        {
          value: "0",
          label: "已下架",
        },
        {
          value: "1",
          label: "已上架",
        },
      ],
      type: "",
      form: {},
      formsort: {
        goodsId: '',
        sortNum: 0,
      },
      dialogVisible: false,
      rulessort: {
        sortNum: [
          { required: true, message: "商品顺序不能为空", trigger: "blur" },
        ],
      },
      //表单校验n
      rules: {
        goodsName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goodsPrice: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        originalPrice: [
          { required: true, message: "请输入商品成本价", trigger: "blur" },
        ],
        costPrice: [
          { required: true, message: "请输入商品成本价", trigger: "blur" },
        ],
        goodsStock: [
          { required: true, message: "请输入商品库存", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入商品发货地", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
      },
      imgUrl: "", //主图
      requestUrl: this.$img.requestUrl,
      previewMainImgList: [],
      previewDetailImgList: [],
      categoryOptions: [],
      auditForm: {},
      detailForm: {},
      open3: false,
      putForm: {},
      fileList: [],
    };
  },

  inject: ["reload"],

  created () {
    this.getList();
    this.getGoodsCategoryList();
  },

  methods: {
    /** 查询商品分类列表 */
    getList () {
      this.loading = true;
      listGoodsInfo(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getGoodsCategoryList () {
      listGoodsCategory().then((response) => {
        this.categoryOptions = response.data;
      });
    },

    handlesort (row) {
      this.resetsort()
      this.formsort.goodsId = row.goodsId;
      this.formsort.sortNum = row.sortNum;
      this.opensort = true
      this.titlesort = "修改商品排序"
    },

    handleView (row) {
      this.detailForm = { ...row };
      this.previewMainImgList = [];
      this.previewMainImgList.push(this.requestUrl + this.detailForm.mainImg);
      this.previewDetailImgList = [];
      row.goodsDetailsImgList.forEach((item) => {
        this.previewDetailImgList.push(this.requestUrl + item.goodsDetailsImg);
      });
      this.open1 = true;
      this.title = "商品详情";
    },
    cancel1 () {
      this.open1 = false;
      this.reset1();
      this.previewMainImgList = [];
      this.previewDetailImgList = [];
    },

    reset1 () {
      this.detailForm = {};
      this.resetForm("detailForm");
    },

    // 新增商品
    handleAdd () {
      this.fileList = [];
      this.goodsDetailsImgList = [];
      this.form = {};
      this.resetForm("detailForm");
      this.open2 = true;
      this.title = "新增商品";
    },

    // 新增商品
    handleUpdate (row) {
      this.form = { ...row };
      this.fileList = [];
      this.goodsDetailsImgList = [];
      this.form.goodsDetailsImgList.forEach((item) => {
        this.fileList.push({
          url: this.requestUrl + item.goodsDetailsImg,
        });
      });
      this.form.goodsDetailsImgList.forEach((item) => {
        this.goodsDetailsImgList.push({
          goodsDetailsImg: item.goodsDetailsImg,
        });
      });
      this.open2 = true;
      this.title = "修改商品";
    },

    // 提交
    submitForm () {
      this.$refs["form"].validate((valid) => {
        // 新增
        if (valid) {
          this.form.goodsDetailsImgList = this.goodsDetailsImgList;
          saveOrUpdate(this.form).then((res) => {
            if (res.code === 200) {
              this.msgSuccess("提交成功");
              this.cancel2();
              this.getList();
              this.reload();
            }
          });
        }
      });
    },
    submitFormsort () {
      this.$refs["formsort"].validate((valid) => {
        // 新增
        if (valid) {

          goodsInfoControllersort(this.formsort).then((res) => {
            if (res.code === 200) {
              this.msgSuccess("修改排序成功");
              this.cancelsort();
              this.getList();
              this.reload();
            }
          });
        }
      });
    },

    cancel2 () {
      this.goodsDetailsImgList = [];
      this.fileList = [];
      this.open2 = false;
      this.reset2();
    },
    cancelsort () {
      this.opensort = false;
      this.resetsort();
    },
    resetsort () {
      // this.formsort = {
      //   goodsId: "",
      //   sortNum: ,
      // };
      this.resetForm("formsort");
    },

    reset2 () {
      this.from = {};
      this.resetForm("from");
    },

    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    audit (row, auditStatus) {
      let _self = this;
      _self.open = true;
      _self.auditForm = {};
      _self.auditForm = { goodsId: row.goodsId, auditStatus: auditStatus };
      let text = "";
      if (auditStatus === -1) {
        text = "拒绝";
      } else {
        text = "通过";
      }
      this.$confirm("确定审核" + text + "该商品吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return audit(_self.auditForm);
        })
        .then(() => {
          this.msgSuccess("审核成功");
          this.getList();
          this.reset3();
          this.reload();
        })
        .catch(function () { });
    },

    putOnOrDown (row, goodsStatus) {
      let _self = this;
      _self.open = true;
      _self.putForm = {};
      _self.putForm = { goodsId: row.goodsId, goodsStatus: goodsStatus };
      let text = "";
      if (goodsStatus === 0) {
        text = "下架";
      } else {
        text = "上架";
      }
      this.$confirm("确定" + text + "该商品吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return putOnOrDown(_self.putForm);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
          this.reset4();
          this.reload();
        })
        .catch(function () { });
    },

    reset3 () {
      this.auditForm = {};
      this.resetForm("auditForm");
    },

    reset4 () {
      this.putForm = {};
      this.resetForm("putForm");
    },

    // 取消按钮
    cancel () {
      this.reset();
      this.open = false;
      this.open1 = false;
      this.open2 = false;
    },

    //表单重置
    reset () {
      this.form = {};
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.resetForm("queryParams");
      this.handleQuery();
    },
    handleRemove (file, fileList) {
      const that = this;
      var imageUrl = "";
      if (file.response) {
        imageUrl = file.response.data.list[0].filePath;
      } else {
        var url = file.url;
        var requestUrl = that.requestUrl;
        imageUrl =
          url.indexOf(requestUrl) != -1 ? url.replace(requestUrl, "") : url;
      }
      const imageList = that.goodsDetailsImgList;
      that.goodsDetailsImgList = imageList.filter(function (item, index) {
        return item.goodsDetailsImg !== imageUrl;
      });
    },
    // 文件上传成功处理
    handleSuccess (response, file, fileList) {
      this.upload.isUploading = false;
      this.goodsDetailsImgList.push({
        goodsDetailsImg: response.data.list[0].filePath,
      });
      this.msgSuccess(response.msg);
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const goodsId = row.goodsId;
      this.$confirm("确定删除该商品吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return removeGoodsInfo(goodsId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
  },
};
</script>
